<!--
 * @Author: guandeshen 295570679@qq.com
 * @Date: 2024-08-20 21:20:43
 * @LastEditors: 关德参 2257609862@qq.com
 * @LastEditTime: 2024-09-15 22:08:33
 * @FilePath: /task-admin/src/views/assets-list/index.vue
 * @Description: 
 * 
 * Copyright (c) 2024 by RSC, All Rights Reserved. 
-->
<template>
  <div class="container">
    <div class="bg-[#fff] border-rd-4px px-24px pt-24px pb-32px">
      <div class="custom-toolbar">
        <span class="custom-title">
          <svg-icon
            v-if="activeBtn"
            @click="handleClose"
            class="mr-8px w-22px h-22px cursor-pointer text-[#4E6BEF]"
            icon-class="back"
          />{{ pageTitle }}
        </span>
        <div class="custom-btn">
          <span
            v-for="item in customBtnList"
            :key="item.prop"
            class="btn"
            :class="{ active: item.prop === activeBtn }"
            @click="handleToolbar(item)"
            ><svg-icon :icon-class="item.icon" />{{ item.label }}</span
          >
        </div>
      </div>
      <el-tabs
        v-model="activeName"
        class="demo-tabs"
        @tab-click="handleTabClick"
      >
        <el-tab-pane name="first">
          <template #label>
            <span class="custom-tabs-label">
              <svg-icon
                class="w-14px h-14px mr-5px text-[#969799]"
                :icon-class="
                  activeName !== 'first'
                    ? 'assetssale-no-select'
                    : 'assetssale-select'
                "
              />
              {{ $t("common.sellingGoods") }}
            </span>
          </template>
          <!-- 物料列表 -->
          <page-content
            v-show="!activeBtn"
            ref="contentRef"
            :stripe="true"
            :content-config="contentConfig"
            @add-click="handleOpenDialog"
            @edit-click="handleOpenDialog"
            @addstock-click="handleAddstockClick"
          >
            <template #status="scope">
              <el-tag :type="scope.row.status == 1 ? 'primary' : 'info'">{{
                scope.row.status == 1 ? $t("common.show") : $t("common.hide")
              }}</el-tag>
            </template>
          </page-content>
          <!-- 日志列表 -->
          <page-content
            v-show="activeBtn"
            ref="stocklogsContentRef"
            :defaultParams="defaultSaleParams"
            :stripe="true"
            :content-config="stocklogsContent"
          />
        </el-tab-pane>
        <el-tab-pane name="second">
          <template #label>
            <span class="custom-tabs-label">
              <svg-icon
                class="w-14px h-14px mr-5px text-[#969799]"
                :icon-class="
                  activeName !== 'second'
                    ? 'assetslease-no-select'
                    : 'assetslease-select'
                "
              />
              {{ $t("common.rentalTools") }}
            </span>
          </template>
          <!-- 列表 -->
          <page-content
            v-show="!activeBtn"
            ref="rentalToolsRef"
            :stripe="true"
            :content-config="rentalToolsConfig"
            @add-click="handleOpenDialog"
            @edit-click="handleOpenDialog"
            @addstock-click="handleAddstockClick"
          >
            <template #status="scope">
              <el-tag :type="scope.row.status == 1 ? 'primary' : 'info'">{{
                scope.row.status == 1 ? $t("common.show") : $t("common.hide")
              }}</el-tag>
            </template>
          </page-content>
          <!-- 日志列表 -->
          <page-content
            v-show="activeBtn"
            ref="stocklogsContentRef"
            :defaultParams="defaultLeaseParams"
            :stripe="true"
            :content-config="stocklogsLeaseContent"
          />
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 新增表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="890px"
      @close="handleCloseDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-position="top"
      >
        <el-row :gutter="32">
          <el-col :span="12">
            <el-form-item :label="$t('common.productName')" prop="asset_name">
              <el-input
                v-model="formData.asset_name"
                :placeholder="$t('common.pleaseEnter')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('common.unitPrice')"
              prop="asset_unit_price"
            >
              <el-input
                v-model="formData.asset_unit_price"
                :placeholder="$t('common.pleaseEnter')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="activeName !== 'first'">
            <el-form-item
              :label="$t('common.originPrice')"
              prop="asset_origin_price"
            >
              <el-input
                v-model="formData.asset_origin_price"
                :placeholder="$t('common.pleaseEnter')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="activeName !== 'first' ? 6 : 12">
            <el-form-item :label="$t('common.unit')" prop="asset_unit">
              <el-input
                v-model="formData.asset_unit"
                :placeholder="$t('common.pleaseEnter')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="activeName !== 'first' ? 6 : 12">
            <el-form-item :label="$t('common.status')" prop="status">
              <el-switch
                v-model="formData.status"
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('common.stock')" prop="asset_qty">
              <el-input-number
                style="width: 100%"
                v-model="formData.asset_qty"
                :min="1"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('common.warningThreshold')"
              prop="waring_threshold"
            >
              <el-input-number
                style="width: 100%"
                v-model="formData.waring_threshold"
                :min="1"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('common.supplier')" prop="supplier_id">
              <el-select
                v-model="formData.supplier_id"
                :placeholder="$t('common.pleaseSelect')"
                @change="handleChange"
              >
                <el-option
                  v-for="item in supplierOptions"
                  :key="item.id"
                  :label="item.s_name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('common.contactInformation')"
              prop="supplier_contact"
            >
              <el-input
                v-model="formData.supplier_contact"
                :placeholder="$t('common.pleaseEnter')"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="32">
          <el-col :span="24">
            <el-form-item :label="$t('common.remark')" prop="remark">
              <el-input
                v-model="formData.remark"
                size="large"
                :placeholder="$t('common.pleaseEnter')"
                type="textarea"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">{{
            $t("common.save")
          }}</el-button>
          <el-button @click="handleCloseDialog">{{
            $t("common.cancel")
          }}</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 供应商管理 -->
    <el-drawer
      v-model="drawerDialog.visible"
      :title="drawerDialog.title"
      size="780px"
      @close="handleDrawerCloseDialog"
    >
      <!-- 供应商管理 -->
      <SupplierManagement v-show="customBtn === 'supplier'" />
      <!-- 商品工具退还管理 -->
      <ProjectReturnManagement
        ref="projectReturnRef"
        :projectOptions="formProjectOptions"
        v-show="customBtn === 'return'"
      />
      <template #footer>
        <div class="dialog-footer" v-show="customBtn === 'return'">
          <el-button type="primary" @click="handleDrawerSubmitClick">{{
            $t("common.save")
          }}</el-button>
          <el-button @click="handleDrawerCloseDialog">{{
            $t("common.cancel")
          }}</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import contentConfig from "./config/content";
import rentalToolsConfig from "./config/rentalToolsContent";
import stocklogsContent from "./config/stocklogsContent";
import stocklogsLeaseContent from "./config/stocklogsLeaseContent";
import type { IObject } from "@/hooks/usePage";
import { AssetssaleForm } from "@/api/assetssale/model";
import type PageContent from "@/components/PageContent/index.vue";
import AssetssaleAPI from "@/api/assetssale";
import AssetsleaseAPI from "@/api/assetslease";
import SupplierAPI from "@/api/supplier";
import { SupplierList } from "@/api/supplier/model";
import type { TabsPaneContext } from "element-plus";
import DashboardAPI from "@/api/dashboard";
import SupplierManagement from "./components/SupplierManagement/index.vue";
import ProjectReturnManagement from "./components/ProjectReturnManagement/index.vue";
import ReturnassetsAPI from "@/api/returnassets";
const { t } = useI18n();
const activeName = ref("first");

const handleTabClick = (tab: TabsPaneContext, event: Event) => {
  rules.asset_origin_price[0].required = tab.paneName == "first" ? false : true;
};

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});
const formData = reactive<AssetssaleForm>({
  status: 1,
  waring_threshold: 1,
  asset_qty: 1,
  asset_type_id: "123",
});

const rules = reactive({
  asset_name: [
    { required: true, message: t("common.pleaseEnter"), trigger: "blur" },
  ],
  asset_unit_price: [
    { required: true, message: t("common.pleaseEnter"), trigger: "blur" },
  ],
  asset_unit: [
    { required: true, message: t("common.pleaseEnter"), trigger: "blur" },
  ],
  supplier_id: [
    { required: true, message: t("common.pleaseSelect"), trigger: "blur" },
  ],
  supplier_contact: [
    { required: true, message: t("common.pleaseEnter"), trigger: "blur" },
  ],
  asset_origin_price: [
    { required: false, message: t("common.pleaseEnter"), trigger: "blur" },
  ],
});

// 新增 / 编辑
function handleOpenDialog(row?: IObject) {
  dialog.visible = true;
  if (row?.id) {
    dialog.title = t("common.modifyProduct");
    Object.assign(formData, row);
  } else {
    dialog.title = t("common.newProduct");
  }
}

// 增加库存
const handleAddstockClick = (row: IObject) => {
  // DictAPI.getbasicInfoFormFormRef.value.formData(id).then((data) => {
  //   Object.assign(basicInfoFormFormRef.value.formData, data);
  // });
};

/** 关闭弹窗 */
const formRef = ref(ElForm);
function handleCloseDialog() {
  dialog.visible = false;
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = undefined;
  formData.status = 1;
  formData.waring_threshold = 1;
  formData.asset_qty = 1;
  formData.asset_type_id = "123";
}

/** 提交表单 */
const loading = ref(false);
const contentRef = ref<InstanceType<typeof PageContent>>();
const rentalToolsRef = ref<InstanceType<typeof PageContent>>();
function handleSubmit() {
  formRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const Id = formData.id;
      const { create_time, ...params } = formData;
      if (activeName.value === "first") {
        AssetssaleAPI.add(params)
          .then(() => {
            ElMessage.success(
              Id
                ? t("common.modifiedSuccessfully")
                : t("common.newSuccessfullyAdded")
            );
            handleCloseDialog();
            contentRef.value?.fetchPageData({}, true); //重置查询
          })
          .finally(() => {
            loading.value = false;
          });
      } else {
        AssetsleaseAPI.add(params)
          .then(() => {
            ElMessage.success(
              Id
                ? t("common.modifiedSuccessfully")
                : t("common.newSuccessfullyAdded")
            );
            handleCloseDialog();
            rentalToolsRef.value?.fetchPageData({}, true); //重置查询
          })
          .finally(() => {
            loading.value = false;
          });
      }
    }
  });
}

// 按钮
const customBtnList = ref([
  {
    prop: "log",
    label: t("common.inboundAndOutboundLogs"),
    icon: "inboundAndOutboundLogs",
  },
  {
    prop: "return",
    label: t("common.projectReturn"),
    icon: "projectReturn",
  },
  {
    prop: "supplier",
    label: t("common.supplierManagement"),
    icon: "supplierManagement",
  },
  // {
  //   prop: "category",
  //   label: t("common.categoryManagement"),
  //   icon: "categoryManagement",
  // },
]);
const activeBtn = ref("");
const pageTitle = ref(t("route.assets"));
const customBtn = ref("");
const handleToolbar = (item: IObject) => {
  customBtn.value = item.prop;
  if (item.prop === "log") {
    activeBtn.value = item.prop;
    pageTitle.value = item.label;
    return;
  }

  if (item.prop === "supplier") {
    drawerDialog.title = t("common.supplierManagement");
    drawerDialog.visible = true;
  }

  if (item.prop === "return") {
    drawerDialog.title = t("common.projectReturnManagement");
    drawerDialog.visible = true;
  }
};
// 返回
const handleClose = () => {
  activeBtn.value = "";
  pageTitle.value = t("route.assets");
};

const defaultSaleParams = ref<IObject>({
  assets_type: "sale",
});
const defaultLeaseParams = ref<IObject>({
  assets_type: "lease",
});

const supplierOptions = ref<SupplierList[]>([]);
const handleChange = (value: any) => {
  const index = supplierOptions.value.findIndex(
    (option) => option.id === value
  );
  formData.supplier_name = supplierOptions.value[index].s_name;
  formData.supplier_contact = supplierOptions.value[index].s_contact;
};

// 供应商管理
// 弹窗
const drawerDialog = reactive({
  title: "",
  visible: false,
});
function handleDrawerCloseDialog() {
  drawerDialog.visible = false;
  // basicInfoFormFormRef2.value.projectFormRef.resetFields();
  // basicInfoFormFormRef2.value.projectFormRef.clearValidate();
  // basicInfoFormFormRef2.value.formData.id = undefined;
  // basicInfoFormFormRef2.value.formData.status = 1;
}

// 项目下拉
const formProjectOptions = ref<Options[]>([]);
const getProjectOptions = async () => {
  const data = await DashboardAPI.getProject({
    page: 1,
    page_size: 10000,
  });
  if (data.list.length > 0) {
    formProjectOptions.value = data.list.map((item) => {
      return {
        value: item.id,
        label: item.p_name,
      };
    });
  }
};

// 退回

const projectReturnRef = ref<InstanceType<
  typeof ProjectReturnManagement
> | null>(null);

const handleDrawerSubmitClick = () => {
  ReturnassetsAPI.returnBack({
    project_id: projectReturnRef.value?.projectId,
    sale_goods: projectReturnRef.value?.saleFormRef?.allTableData.map(
      (item) => {
        return {
          id: item.id,
          name: item.asset_name,
          num: item.num,
        };
      }
    ),
    lease_goods: projectReturnRef.value?.leaseFormRef?.allTableData.map(
      (item) => {
        return {
          id: item.id,
          name: item.asset_name,
          num: item.num,
        };
      }
    ),
    images: projectReturnRef.value?.multiPicUrls,
  })
    .then(() => {
      ElMessage.success(t("common.refundSuccessful"));
      handleDrawerCloseDialog();
      projectReturnRef.value?.initReturn();
    })
    .finally(() => {
      loading.value = false;
    });
};

onMounted(() => {
  SupplierAPI.getPage({
    page: 1,
    page_size: 100000,
  }).then((data) => {
    // console.log("%c Line:426 🍓 data", "color:#f5ce50", data);
    supplierOptions.value = data.list;
  });
  getProjectOptions();
});
</script>

<style lang="scss" scoped>
:deep(.table-box) {
  margin-top: 0 !important;
  padding: 0 !important;
}
:deep(.el-tabs__header) {
  margin-bottom: 0 !important;
}
.custom-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 16px;
  .custom-title {
    display: flex;
    align-items: center;
    color: #323233;
    font-family: "PingFang SC";
    font-size: 16px;
    font-weight: 900;
    text-transform: capitalize;
    &::before {
      content: "";
      display: inline-block;
      width: 3px;
      height: 22px;
      margin-right: 8px;
      background: #4e6bef;
    }
  }
  .custom-btn {
    display: flex;
    justify-content: flex-end;
    .btn {
      display: flex;
      padding: 0 8px;
      margin-left: 8px;
      height: 30px;
      justify-content: center;
      align-items: center;
      border-radius: 3px;
      background: #f2f3f5;
      border: 1px solid #f2f3f5;
      box-sizing: border-box;
      cursor: pointer;
      font-size: 14px;
      font-weight: 500;
      color: #323233;
      .svg-icon {
        width: 14px;
        height: 14px;
        margin-right: 5px;
      }
      &.active,
      &:hover {
        border: 1px solid #4e6bef;
        background: #eff1fe;
        color: #4e6bef;
      }
    }
  }
}

:deep(.el-drawer__header) {
  margin-bottom: 0 !important;
}
/* @import url(); 引入公共css类 */
</style>
